package json;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONWriter;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/*
* FASTJSON2实现java对象和JSON数据的互转
*   1.将java对象(普通对象，集合，map)转换为json字符串
*       JSON.toJSONString()
*   2.将json字符串转化为java对象
*       JSON.parseObject()
*   3.将含有数组的json字符串解析成java的集合对象
*       JSONArray.parseArray()
*
*
* */
public class JSONTest02 {
    /*将java对象转化为JSON格式*/
    @Test
    public void testObjectToJson() {
        Student student = new Student(20131210, "无忌", "男", 25);
        System.out.println(JSON.toJSONString(student));
    }

    /*将JSON格式转化为java对象*/
    @Test
    public void testJsonToObject() {
        String jsonStr = "{\"age\":25,\"sgender\":\"男\",\"sname\":\"无忌\",\"sno\":20131210}";
        Student student = JSON.parseObject(jsonStr, Student.class);
        System.out.println(student);
    }
    /*将一个集合转换成json*/
    @Test
    public void testListToJSON() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }

    /*将一个json转换成集合*/
    @Test
    public void testJSONtToList() {
        String jsonStr = "[{\"age\":25,\"gender\":\"男\",\"sname\":\"无忌\",\"sno\":20131210},{\"age\":20,\"gender\":\"女\",\"sname\":\"敏敏\",\"sno\":20131223}]";
        JSONArray.parseArray(jsonStr, Student.class).forEach(System.out::println);
    }

    /*将map转换成json串*/
    @Test
    public void testMapToJson() {
        List<Student> students = Arrays.asList(
                new Student(20131210, "无忌", "男", 25),
                new Student(20131223, "敏敏", "女", 20)
        );
        Map<String, Student> map = students.stream().collect(Collectors.toMap(stu -> stu.getSno() + "", stu -> stu));

        System.out.println(JSON.toJSONString(students));
        System.out.println(JSON.toJSONString(students, JSONWriter.Feature.PrettyFormat));
    }
}
